import { Component, OnInit } from '@angular/core'
import { Location } from '@angular/common'
import { Router, ActivatedRoute, Params } from '@angular/router'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { ActivityService } from '../activity/services/activity.service'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'

@Component({
  selector: 'app-activity-detail',
  templateUrl: './activity-detail.component.html',
  styleUrls: ['./activity-detail.component.scss']
})
export class ActivityDetailComponent implements OnInit {
  // 活动ID
  promotion = ''

  // 活动详情
  detail: any
  error = false
  loading = false
  // 活动是否下线
  forbidden = false

  constructor(
    private location: Location,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utils: CommonUtil,
    private service: ActivityService,
    private localStorage: CoolLocalStorage
  ) {}

  // 初始化
  ngOnInit() {
    this.loading = true
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      this.promotion = params.promotion
      this.getDetail(params.promotion)
    })
  }
  // 返回
  onClickLeft() {
    this.location.back()
  }
  // 获取活动详情
  getDetail(id) {
    this.service.getDetail(
      id,
      res => {
        setTimeout(() => {
          this.error = false
          this.loading = false
        }, 500)
        if (res.Success && res.Result) {
          let detail = res.Result
          detail.LeftTime = this.utils.getTimeDiff(
            new Date().getTime(),
            new Date(detail.End.replace(/-/g, '/')).getTime()
          )
          detail.Description = JSON.parse(detail.Description)
          detail.Photo = this.utils.getPhotoByName(detail.Photo, '活动图片')
          this.detail = detail
        }
        if (res.Success && !res.Result) {
          this.forbidden = true
        }
      },
      () => {
        setTimeout(() => {
          this.error = true
          this.loading = false
        }, 500)
      }
    )
  }
  // 刷新
  handleReload() {
    this.error = false
    this.loading = true
    this.getDetail(this.promotion)
  }
}
